library(automap)
library(gstat)
library(dplyr)
source('R/predict_gstat_par.R')
#   automatically fit variogram with automap  
# set the formula of ordinary krige
formula.volume_rate<-'volume_rate~1'%>%as.formula
ha_info.sp$real.volume<-!is.na(ha_info.sp$volume_rate)
valid.volume_rate<-ha_info.sp[ha_info.sp$real.volume,]%>%
    spTransform(CRSobj = crs(poi.diversity))%>%remove.duplicates
pre.volume_rate<-ha_info.sp[!ha_info.sp$real.volume,]%>%
    spTransform(CRSobj = crs(poi.diversity))
mm<-autofitVariogram(formula.volume_rate, valid.volume_rate)
volume_rate.krige.fit <- gstat(NULL,
                               formula =formula.volume_rate,
                               data =valid.volume_rate,
                               model=mm$var_model)
valid.volume_rate.pre<-predict.gstat.par(volume_rate.krige.fit,
                                           s=pre.volume_rate)
ha_info.sp$volume_rate[!ha_info.sp$real.volume]<-
    valid.volume_rate.pre$var1.pred

formula.greening_rate<-'greening_rate~1'%>%as.formula
ha_info.sp$real.greening<-!is.na(ha_info.sp$greening_rate)
valid.greening_rate<-ha_info.sp[ha_info.sp$real.greening,]%>%
    spTransform(CRSobj = crs(poi.diversity))%>%remove.duplicates
pre.greening_rate<-ha_info.sp[!ha_info.sp$real.greening,]%>%
    spTransform(CRSobj = crs(poi.diversity))
# zerodist(valid.greening_rate) make sure there is no duplicates
mm<-autofitVariogram(formula.greening_rate, valid.greening_rate)
greening_rate.krige.fit <- gstat(NULL,
                               formula =formula.greening_rate,
                               data =valid.greening_rate,
                               model=mm$var_model)
valid.greening_rate.pre<-predict.gstat.par(greening_rate.krige.fit,
                                         s=pre.greening_rate)
ha_info.sp$greening_rate[!ha_info.sp$real.greening]<-
    valid.greening_rate.pre$var1.pred